package com.itheima.service;

import com.itheima.pojo.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zero
 * @date 2020/5/30
 */
public class SpringSecurityUserService implements UserDetailsService {

    /**
     * 模拟数据库中的用户数据
     */
    public  static Map<String, User> map = new HashMap<>();
    static {
        User user1 = new User();
        user1.setUsername("admin");
        user1.setPassword("admin");

        User user2 = new User();
        user2.setUsername("xiaoming");
        user2.setPassword("1234");

        map.put(user1.getUsername(),user1);
        map.put(user2.getUsername(),user2);
    }

    /**
     * 根据用户名加载用户信息,并返回给security框架
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        User user = map.get(username);

        if (user == null){
            //用户在数据库中不存在
            return null;
        }else{
            //用户存在,需要授权权限
            List<GrantedAuthority> list = new ArrayList<>();
            //相同则授予权限
            if ("admin".equals(username)){
                list.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
            }
            //返回框架提供的user对象
            return new org.springframework.security.core.userdetails.User(username,"{noop}"+user.getPassword(),list);
        }
    }
}
